import { ref, computed } from 'vue'
import { defineStore, } from 'pinia'
import HttpRepositiry from '@/repositorys/HttpRepositiry';
import { cache, showConfirm, showLoading, showToast } from '@/utils/utils';
import router from '@/router';
import { useMonitor } from './monitor';

export const useSession = defineStore('session', () => {
    const token = ref<string>(cache.get('token') || '');
    const nick = ref('');
    const id = ref('');
    const topic = ref('');
    const expireTime = ref(0);
    const isLogin = computed(() => !!token.value);
    const isBind = ref(false);
    const isBan = ref(false);

    const nowTime = ref(Date.now());
    const isExpire = computed(() => {
        const is = expireTime.value * 1000 <= nowTime.value;
        return is;
    });

    const downUrl = ref('');

    const monitor = useMonitor();

    setInterval(() => {
        nowTime.value = Date.now();
    }, 1000);

    const online = async () => {
        if (!isLogin.value) {
            return;
        }
        const res = await HttpRepositiry.online();
        if (res.status == 200) {
            // 封号
            if (res.data.body.status != 0) {
                isBan.value = true;
                expireTime.value = 0;
                await showConfirm('账号已封禁!');
                loginout();
                return;

            }
        }

        setTimeout(() => {
            online();
        }, 1000 * 20);
    }


    const pull = async () => {
        const res = await HttpRepositiry.getAnchor();
        if (res.status == 200) {
            const data = res.data.body;
            nick.value = data.nick;
            id.value = data.anchorId;
            isBind.value = !!data.anchorId;
            expireTime.value = isBan.value ? 0 : data.expireTime;
        }
    }

    const resolving = async (tkl: string) => {
        const loading = showLoading();
        const res = await HttpRepositiry.resolvingAnchor({
            tkl
        });
        loading.close();
        if (res.status == 200) {
            const data = res.data.body;
            nick.value = data.nick;
            id.value = data.anchorId;
        }
    }
    const bind = async (): Promise<boolean> => {
        const res = await HttpRepositiry.bindAnchor({
            nick: nick.value,
            anchorId: id.value
        });
        isBind.value = res.status == 200;

        return res.status == 200;
    }

    const live = async (tkl: string) => {
        if (!isBind.value) {
            return showToast('请先绑定主播');
        }
        const res = await HttpRepositiry.live({
            tkl
        });
        if (res.status == 200) {
            const data = res.data.body;
            nick.value = data.nick;
            id.value = data.anchorId;
            topic.value = data.topic;
            return showToast('刷新成功');
        }
    }

    const login = async (username: string, password: string): Promise<boolean> => {
        const loading = showLoading();
        const res = await HttpRepositiry.login({
            username: username,
            password: password,
        });
        loading.close();
        if (res.status == 200) {
            const data = res.data.body;
            if (data.status != 0) {
                showConfirm('账号已封禁!');
                return false;
            }

            token.value = data.token;
            cache.set('token', data.token);
            nick.value = data.nick;
            id.value = data.anchorId;
            expireTime.value = data.expireTime;
            update();
            online();
            return true;
        }
        return false;
    }
    const register = async (username: string, password: string, code: string): Promise<boolean> => {
        const res = await HttpRepositiry.register({
            username: username,
            password: password,
            code: code
        });
        if (res.status == 200) {
            return true;
        }
        return false;
    }


    const loginout = () => {
        cache.set('token', '');
        token.value = '';
        nick.value = '';
        id.value = '';
        topic.value = '';
        expireTime.value = 0;
        isBind.value = false;
        isBan.value = false;
        router.replace('/login');
    }


    const update = async () => {
        if (!isLogin) {
            return;
        }
        const res = await HttpRepositiry.update();
        if (res.status == 200) {
            const newVersions = res.data.body.version2.split('.');
            const url = res.data.body.url;
            const version = window.api.getAppVersion();
            const oldVersions = version.split('.');
            downUrl.value = url;
            let isUpdate = false;
            const n0 = parseInt(newVersions[0]);
            const o0 = parseInt(oldVersions[0]);

            const n1 = parseInt(newVersions[1]);
            const o1 = parseInt(oldVersions[1]);

            const n2 = parseInt(newVersions[2]);
            const o2 = parseInt(oldVersions[2]);
            if (n0 > o0) {
                isUpdate = true;
            }
            if (n0 == o0 && n1 > o1) {
                isUpdate = true;
            }
            if (n0 == o0 && n1 == o1 && n2 > o2) {
                isUpdate = true;
            }
            if (isUpdate) {
                router.replace('/update');
            }
        }

    }



    const init = () => {
        update();
        online();
    }






    return { token, nick, expireTime, id, topic, isLogin, login, register, resolving, bind, pull, isBind, live, loginout, downUrl, isExpire, nowTime, init }
});


